package com.xc.quickstart.common.aspect;


import com.xc.quickstart.common.annotation.GlobalApiResponse;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import com.xc.quickstart.common.model.ApiResponse;

/**
 * @author yinyansheng
 */
@RestControllerAdvice("com.xc.quickstart.api.controller")
@Slf4j
public class GlobalApiResponseControllerAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> clazz) {
        return true;
    }

    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> converter
            , ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if (body instanceof ApiResponse) {
            return body;
        }

        GlobalApiResponse globalApiResponse = methodParameter.getMethod().getAnnotation(GlobalApiResponse.class);
        if (null == globalApiResponse) {
            globalApiResponse = methodParameter.getDeclaringClass().getAnnotation(GlobalApiResponse.class);
        }

        if (null == globalApiResponse || globalApiResponse.ignore()) {
            return body;
        }

        return ApiResponse.ok(body);
    }
}